﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using OpenLS.Spreadsheet.UI.Internals;
using OpenLS.Spreadsheet.UI.Internals.Resources;

namespace OpenLS.Spreadsheet.UI
{
    
    static class GridValidation
    {
        internal static void EnableCommands(UIElement grid)
        {
            grid.CommandBindings.Add(new CommandBinding(SpreadsheetCommands.SetDataValidation, OnSetDataValidation, OnTrue));
            grid.CommandBindings.Add(new CommandBinding(SpreadsheetCommands.ClearDataValidation, OnClearDataValidation, OnTrue));
        }

        private static void OnTrue(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private static void OnClearDataValidation(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet ws = SpreadsheetElement.GetWorksheet(sender);
            foreach (var validation in Enumerable.ToList(Enumerable.Where(ws.DataValidations, v => Range.Intersects(v.Range, ws.Selection))))
            {
                ws.DataValidations.Remove(validation);
            }
            e.Handled = true;
        }

        private static void OnSetDataValidation(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet ws = SpreadsheetElement.GetWorksheet(sender);
            DataValidation validation;
            List<DataValidation> validations =
                Enumerable.ToList(Enumerable.Where(ws.DataValidations, vv => Range.Intersects(vv.Range, ws.Selection)));
            switch (validations.Count)
            {
                case 0:
                    validation = new DataValidation
                                     {
                                         Range = ws.Selection,
                                         AllowBlank = true,
                                         ShowInputMessage = true,
                                         ShowErrorMessage = true
                                     };
                    break;
                case 1:
                    validation = validations[0];
                    break;
                default:
                    validation = validations[0];  //\\ should extend here
                    break;
            }


            var dataValidation = new DataValidationViewModel(validation);
            if (PropertyHelper.ShowPropertiesNonHostedFor((FrameworkElement) sender, UIStringTable.DataValidation,  dataValidation, new DataValidationResources()))
            {

                foreach (var v in Enumerable.ToList(Enumerable.Where((ws.DataValidations), vv => Range.Intersects(vv.Range, ws.Selection))))
                {
                    ws.DataValidations.Remove(v);
                }
                ws.DataValidations.Add(dataValidation.Model);

           
            }
            e.Handled = true;
        }
    }
}